<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <img src="/logo.png" alt="家政服务平台" />
          <span>家政服务平台</span>
        </div>
        <el-icon @click="toggleSidebar"><Menu /></el-icon>
        <el-icon @click="refreshData"><Refresh /></el-icon>
        <span class="nav-text">家政人员管理</span>
      </div>
      <div class="header-right">
        <el-button class="client-btn">
          <el-icon><Monitor /></el-icon>
          客户端
        </el-button>
        <el-badge is-dot>
          <el-icon><Bell /></el-icon>
        </el-badge>
        <el-icon><Setting /></el-icon>
        <el-dropdown @command="handleCommand">
          <div class="user-info">
            <el-avatar :size="32">{{ userInitials }}</el-avatar>
            <span>{{ username }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="settings">账号设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <span style="color: #f56c6c;">注销</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="main-container">
      <!-- 左侧菜单 -->
      <el-aside width="64px" class="sidebar">
        <router-link to="/admin" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><HomeFilled /></el-icon>
            <span>首页</span>
          </div>
        </router-link>
        <router-link to="/admin/service-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><Setting /></el-icon>
            <span>服务管理</span>
          </div>
        </router-link>
        <router-link to="/admin/user-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </div>
        </router-link>
        <router-link to="/admin/application-management" custom v-slot="{ navigate }">
          <div class="menu-item" @click="navigate">
            <el-icon><Promotion /></el-icon>
            <span>审批系统</span>
          </div>
        </router-link>
        <router-link to="/admin/worker-management" custom v-slot="{ navigate }">
          <div class="menu-item active" @click="navigate">
            <el-icon><UserFilled /></el-icon>
            <span>家政管理</span>
          </div>
        </router-link>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main-content">
        <div class="worker-management">
          <div class="page-header">
            <h2>家政人员管理</h2>
            <div class="header-actions">
              <el-button @click="refreshData">
                <el-icon><Refresh /></el-icon>刷新
              </el-button>
            </div>
          </div>

          <!-- 筛选器区域 -->
          <el-card class="filter-container">
            <div class="filter-form">
              <el-form :model="filterForm" inline>
                <el-form-item label="姓名">
                  <el-input v-model="filterForm.name" placeholder="搜索姓名" clearable />
                </el-form-item>
                <el-form-item label="服务类型">
                  <!-- 修改下拉框显示已选中的选项 -->
                  <el-select v-model="filterForm.serviceType" placeholder="选择服务类型" clearable
                             popper-class="custom-select-dropdown">
                    <!-- 自定义触发器内容 -->
                    <template #prefix v-if="filterForm.serviceType">
                      <el-tag size="small" type="info" class="select-tag">
                        {{ filterForm.serviceType }}
                      </el-tag>
                    </template>
                    <el-option label="清洁服务" value="清洁服务">
                      <div class="select-option-content">
                        <el-tag size="small" type="info">清洁服务</el-tag>
                      </div>
                    </el-option>
                    <el-option label="照护服务" value="照护服务">
                      <div class="select-option-content">
                        <el-tag size="small" type="info">照护服务</el-tag>
                      </div>
                    </el-option>
                    <el-option label="烹饪服务" value="烹饪服务">
                      <div class="select-option-content">
                        <el-tag size="small" type="info">烹饪服务</el-tag>
                      </div>
                    </el-option>
                    <el-option label="维修服务" value="维修服务">
                      <div class="select-option-content">
                        <el-tag size="small" type="info">维修服务</el-tag>
                      </div>
                    </el-option>
                    <el-option label="其他服务" value="其他服务">
                      <div class="select-option-content">
                        <el-tag size="small" type="info">其他服务</el-tag>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="工作状态">
                  <!-- 修改下拉框显示已选中的选项 -->
                  <el-select v-model="filterForm.status" placeholder="选择状态" clearable
                             popper-class="custom-select-dropdown">
                    <!-- 自定义触发器内容 -->
                    <template #prefix v-if="filterForm.status">
                      <el-tag
                          size="small"
                          :type="filterForm.status === '在职' ? 'success' : 'danger'"
                          class="select-tag">
                        {{ filterForm.status }}
                      </el-tag>
                    </template>
                    <el-option label="在职" value="在职">
                      <div class="select-option-content">
                        <el-tag size="small" type="success">在职</el-tag>
                      </div>
                    </el-option>
                    <el-option label="不在职" value="不在职">
                      <div class="select-option-content">
                        <el-tag size="small" type="danger">不在职</el-tag>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="加入日期">
                  <el-date-picker
                      v-model="filterForm.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleFilter">筛选</el-button>
                  <el-button @click="resetFilter">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>

          <!-- 数据表格 -->
          <el-card class="table-container">
            <div class="table-header">
              <div class="statistics">
                <el-tag type="success" effect="dark">在职: {{ counts.active }}</el-tag>
                <el-tag type="danger" effect="dark">不在职: {{ counts.inactive }}</el-tag>
                <el-tag type="info" effect="dark">总计: {{ counts.total }}</el-tag>
              </div>
              <div class="table-actions">
                <el-tooltip content="导出数据" placement="top">
                  <el-button :icon="Download" circle />
                </el-tooltip>
                <el-tooltip content="列设置" placement="top">
                  <el-button :icon="SetUp" circle />
                </el-tooltip>
              </div>
            </div>

            <el-table
                :data="workerList"
                style="width: 100%"
                border
                stripe
                v-loading="loading"
                row-key="id"
                @row-click="handleRowClick"
                table-layout="fixed"
            >
              <el-table-column type="index" width="60" align="center" />
              <el-table-column prop="id" label="ID" width="70" sortable align="center" />
              <el-table-column prop="name" label="姓名" width="90" align="center" />
              <el-table-column prop="gender" label="性别" width="60" align="center" />
              <el-table-column prop="age" label="年龄" width="60" align="center" sortable />
              <!-- 地址列 -->
              <el-table-column prop="address" label="地址" width="150" align="center" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.address || '暂无地址' }}
                </template>
              </el-table-column>
              <el-table-column prop="serviceType" label="服务类型" width="150">
                <template #default="scope">
                  <el-tag
                      v-for="(type, index) in formatServiceTypes(scope.row.serviceType)"
                      :key="index"
                      style="margin-right: 5px; margin-bottom: 5px;"
                      size="small"
                  >
                    {{ type }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- 工作经验列 -->
              <el-table-column prop="workExperience" label="工作经验" min-width="180" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.workExperience || '暂无工作经验' }}
                </template>
              </el-table-column>
              <el-table-column prop="joinDate" label="加入日期" width="110" sortable align="center" />
              <el-table-column prop="status" label="状态" width="80" align="center">
                <template #default="scope">
                  <el-tag
                      :type="scope.row.status === '在职' ? 'success' : 'danger'"
                      size="small"
                  >
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right" align="center">
                <template #default="scope">
                  <el-button
                      type="primary"
                      size="small"
                      @click.stop="viewWorkerDetails(scope.row)"
                  >
                    查看
                  </el-button>
<!--                  <el-button-->
<!--                      type="warning"-->
<!--                      size="small"-->
<!--                      @click.stop="handleEditWorker(scope.row)"-->
<!--                  >-->
<!--                    编辑-->
<!--                  </el-button>-->
                  <el-button
                      type="danger"
                      size="small"
                      @click.stop="handleDeleteWorker(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                  background
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="totalWorkers"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </div>

        <!-- 家政人员详情对话框 -->
        <el-dialog
            v-model="detailDialogVisible"
            title="家政人员详情"
            width="65%"
        >
          <div v-if="selectedWorker" class="worker-detail">
            <!-- 基本信息 -->
            <el-card class="detail-section" shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>基本信息</h3>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="detail-item">
                    <span class="label">姓名：</span>
                    <span class="value">{{ selectedWorker.name }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="detail-item">
                    <span class="label">性别：</span>
                    <span class="value">{{ selectedWorker.gender }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="detail-item">
                    <span class="label">年龄：</span>
                    <span class="value">{{ selectedWorker.age }}岁</span>
                  </div>
                </el-col>
              </el-row>
            </el-card>

            <!-- 工作信息 -->
            <el-card class="detail-section" shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>工作信息</h3>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="detail-item">
                    <span class="label">工作状态：</span>
                    <el-tag
                        :type="selectedWorker.status === '在职' ? 'success' : 'danger'"
                        size="small"
                    >
                      {{ selectedWorker.status }}
                    </el-tag>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="detail-item">
                    <span class="label">加入日期：</span>
                    <span class="value">{{ selectedWorker.joinDate }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="detail-item">
                    <span class="label">工作评分：</span>
                    <el-rate v-model="workerRating" disabled text-color="#ff9900" />
                  </div>
                </el-col>
              </el-row>

              <el-divider content-position="left">服务类型</el-divider>

              <div class="service-types">
                <el-tag
                    v-for="(type, index) in formatServiceTypes(selectedWorker.serviceType)"
                    :key="index"
                    class="service-tag"
                >
                  {{ type }}
                </el-tag>
              </div>

              <el-divider content-position="left">工作经验</el-divider>

              <div class="work-experience">
                {{ selectedWorker.workExperience }}
              </div>
            </el-card>

            <!-- 服务统计 -->
            <el-card class="detail-section" shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>服务统计</h3>
                </div>
              </template>

              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="stat-card">
                    <div class="stat-value">{{ workerStats.completedOrders }}</div>
                    <div class="stat-label">完成订单</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="stat-card">
                    <div class="stat-value">{{ workerStats.totalHours }}</div>
                    <div class="stat-label">服务时长(小时)</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="stat-card">
                    <div class="stat-value">{{ workerStats.satisfactionRate }}%</div>
                    <div class="stat-label">满意度</div>
                  </div>
                </el-col>
              </el-row>

              <el-divider content-position="left">近期服务</el-divider>

              <el-table :data="recentServices" stripe style="width: 100%">
                <el-table-column prop="date" label="日期" width="110" />
                <el-table-column prop="serviceType" label="服务类型" width="120" />
                <el-table-column prop="customer" label="客户" width="100" />
                <el-table-column prop="duration" label="时长(小时)" width="100" align="center" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag
                        :type="scope.row.status === '已完成' ? 'success' :
                            scope.row.status === '进行中' ? 'primary' : 'info'"
                        size="small"
                    >
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="rating" label="评分" width="120">
                  <template #default="scope">
                    <el-rate v-model="scope.row.rating" disabled text-color="#ff9900" />
                  </template>
                </el-table-column>
              </el-table>
            </el-card>

            <!-- 技能评估 -->
            <el-card class="detail-section" shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>技能评估</h3>
                </div>
              </template>

              <el-row :gutter="20">
                <el-col :span="12" v-for="(skill, index) in workerSkills" :key="index">
                  <div class="skill-item">
                    <span class="skill-name">{{ skill.name }}</span>
                    <el-progress
                        :percentage="skill.level"
                        :color="customProgressColors"
                        :format="format => `${format}%`"
                    />
                  </div>
                </el-col>
              </el-row>
            </el-card>

            <!-- 客户评价 -->
            <el-card class="detail-section" shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>客户评价</h3>
                  <el-button type="text" @click="loadMoreReviews">查看更多</el-button>
                </div>
              </template>

              <div v-if="customerReviews.length === 0" class="no-reviews">
                暂无客户评价
              </div>

              <div v-else class="review-list">
                <div v-for="(review, index) in customerReviews" :key="index" class="review-item">
                  <div class="review-header">
                    <div class="reviewer-info">
                      <el-avatar :size="40">{{ review.customer.charAt(0) }}</el-avatar>
                      <div class="reviewer-detail">
                        <div class="reviewer-name">{{ review.customer }}</div>
                        <div class="review-date">{{ review.date }}</div>
                      </div>
                    </div>
                    <div class="review-rating">
                      <el-rate v-model="review.rating" disabled text-color="#ff9900" />
                    </div>
                  </div>
                  <div class="review-content">
                    {{ review.content }}
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-dialog>

        <!-- 编辑/添加家政人员对话框 -->
        <el-dialog
            v-model="editDialogVisible"
            :title="isEdit ? '编辑家政人员' : '添加家政人员'"
            width="50%"
        >
          <el-form :model="workerForm" ref="workerFormRef" :rules="workerRules" label-width="100px">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="workerForm.name" />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="workerForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="workerForm.age" :min="18" :max="65" />
            </el-form-item>

            <el-form-item label="服务类型" prop="serviceTypeArray">
              <el-select v-model="workerForm.serviceTypeArray" multiple placeholder="请选择服务类型">
                <el-option label="清洁服务" value="清洁服务" />
                <el-option label="照护服务" value="照护服务" />
                <el-option label="烹饪服务" value="烹饪服务" />
                <el-option label="维修服务" value="维修服务" />
                <el-option label="其他服务" value="其他服务" />
              </el-select>
            </el-form-item>

            <el-form-item label="工作状态" prop="status">
              <el-select v-model="workerForm.status">
                <el-option label="在职" value="在职" />
                <el-option label="不在职" value="不在职" />
              </el-select>
            </el-form-item>

            <el-form-item label="加入日期" prop="joinDate">
              <el-date-picker
                  v-model="workerForm.joinDate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item label="工作经验" prop="workExperience">
              <el-input
                  v-model="workerForm.workExperience"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入工作经验描述"
              />
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="editDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitWorkerForm" :loading="submitting">
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  HomeFilled, Menu, Setting, Bell, Monitor, CaretBottom, Refresh,
  User, UserFilled, Plus, Download, SetUp, Promotion
} from '@element-plus/icons-vue'
import axios from "axios";
import {addWorker, deleteWorkerById, getWorkerList, updateWorker} from "@/api/worker/worker.js";

const router = useRouter()
const username = ref('admin')
const userInitials = computed(() => {
  return username.value.charAt(0).toUpperCase()
})

// 侧边栏控制
const isCollapse = ref(false)
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 处理用户菜单
const handleCommand = (command) => {
  if (command === 'logout') {
    logout()
  } else if (command === 'profile') {
    // 处理个人信息
    ElMessage.info('功能开发中')
  } else if (command === 'settings') {
    // 处理账号设置
    ElMessage.info('功能开发中')
  }
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token')
    ElMessage({
      type: 'success',
      message: '已成功退出登录'
    })
    router.push('/login')
  }).catch(() => {})
}

// 状态和变量
const loading = ref(false)
const workerList = ref([]) // 表格显示的工作者列表（经过筛选和分页）
const allWorkers = ref([]) // 所有工作者数据，用于本地筛选
const filteredWorkers = ref([]) // 筛选后的结果，用于分页
const totalWorkers = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const filterForm = reactive({
  name: '',
  serviceType: '',
  status: '',
  dateRange: []
})

// 统计数量
const counts = reactive({
  active: 0,
  inactive: 0,
  total: 0
})

// 从后端获取所有家政人员数据（只在页面加载和点刷新按钮时调用）
const fetchWorkerData = async () => {
  loading.value = true;
  try {
    const response = await getWorkerList();

    // 检查并确保 response.data 是数组
    if (response.data && Array.isArray(response.data)) {
      allWorkers.value = response.data;
    } else if (response.data && Array.isArray(response.data.data)) {
      // 有些 API 会将数据包装在 data 字段中
      allWorkers.value = response.data.data;
    } else {
      console.error('API 返回的数据不是数组格式:', response.data);
      allWorkers.value = [];
      ElMessage.error('获取的数据格式不正确');
    }

    // 重置筛选和分页
    currentPage.value = 1;

    // 应用本地筛选
    applyLocalFilters();

  } catch (error) {
    console.error('获取家政人员数据失败:', error);
    ElMessage.error('获取家政人员数据失败');
    workerList.value = [];
    allWorkers.value = [];
    filteredWorkers.value = [];
    totalWorkers.value = 0;
    counts.total = 0;
    counts.active = 0;
    counts.inactive = 0;
  } finally {
    loading.value = false;
  }
};

// 本地筛选函数（不调用后端接口）
const applyLocalFilters = () => {
  // 确保 allWorkers.value 是数组
  if (!Array.isArray(allWorkers.value)) {
    console.warn('allWorkers.value 不是数组:', allWorkers.value);
    filteredWorkers.value = [];
    workerList.value = [];
    counts.total = 0;
    counts.active = 0;
    counts.inactive = 0;
    totalWorkers.value = 0;
    return;
  }

  // 本地过滤数据
  let filtered = [...allWorkers.value];

  // 应用过滤条件
  if (filterForm.name) {
    filtered = filtered.filter(item =>
        item.name && item.name.toLowerCase().includes(filterForm.name.toLowerCase())
    );
  }

  if (filterForm.serviceType) {
    filtered = filtered.filter(item =>
        item.serviceType && item.serviceType.includes(filterForm.serviceType)
    );
  }

  if (filterForm.status) {
    filtered = filtered.filter(item => item.status === filterForm.status);
  }

  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    const [startDate, endDate] = filterForm.dateRange;
    filtered = filtered.filter(item => {
      if (!item.joinDate) return false;
      const itemDate = new Date(item.joinDate);
      return itemDate >= new Date(startDate) && itemDate <= new Date(endDate);
    });
  }

  // 保存筛选后的结果
  filteredWorkers.value = filtered;

  // 更新统计
  updateStatistics();

  // 应用分页
  applyPagination();
};

// 应用分页
const applyPagination = () => {
  totalWorkers.value = filteredWorkers.value.length;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  workerList.value = filteredWorkers.value.slice(start, end);
};

// 更新统计信息
const updateStatistics = () => {
  counts.total = filteredWorkers.value.length;
  counts.active = filteredWorkers.value.filter(item => item.status === '在职').length;
  counts.inactive = filteredWorkers.value.filter(item => item.status === '不在职').length;
};

// 筛选按钮处理
const handleFilter = () => {
  currentPage.value = 1;
  applyLocalFilters();
};

// 重置筛选
const resetFilter = () => {
  filterForm.name = '';
  filterForm.serviceType = '';
  filterForm.status = '';
  filterForm.dateRange = [];
  currentPage.value = 1;
  applyLocalFilters();
};

// 刷新数据（重新从后端获取）
const refreshData = () => {
  fetchWorkerData();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  applyPagination();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  applyPagination();
};

// 详情对话框
const detailDialogVisible = ref(false)
const selectedWorker = ref(null)
const workerRating = ref(4.5)
const workerStats = reactive({
  completedOrders: 45,
  totalHours: 180,
  satisfactionRate: 98
})
const customProgressColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#6f7ad3', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#5cb87a', percentage: 100 }
]
const workerSkills = ref([])
const recentServices = ref([])
const customerReviews = ref([])

// 格式化服务类型为数组
const formatServiceTypes = (serviceTypeStr) => {
  if (!serviceTypeStr) return []
  return serviceTypeStr.split(',')
}

// 行点击处理
const handleRowClick = (row) => {
  viewWorkerDetails(row)
}

// 查看工作详情
const viewWorkerDetails = (worker) => {
  selectedWorker.value = {...worker}
  updateWorkerDetailsData(worker)
  detailDialogVisible.value = true
}

// 更新工作者详情数据
const updateWorkerDetailsData = (worker) => {
  // 根据工作经验和服务类型生成评分和技能
  const expYears = getExperienceYears(worker.workExperience)

  // 更新评分 (3.8-5.0)
  workerRating.value = Math.min(5.0, 3.8 + (expYears * 0.15))

  // 更新技能
  updateWorkerSkills(worker)

  // 更新服务统计
  workerStats.completedOrders = Math.floor(expYears * 15 + Math.random() * 20)
  workerStats.totalHours = Math.floor(expYears * 60 + Math.random() * 50)
  workerStats.satisfactionRate = Math.floor(90 + Math.random() * 10)

  // 更新近期服务
  updateRecentServices(worker)

  // 更新客户评价
  updateCustomerReviews(worker)
}

// 从工作经验中获取年数
const getExperienceYears = (experience) => {
  if (!experience) return 1
  const match = experience.match(/(\d+)年/)
  return match ? parseInt(match[1]) : 1
}

// 更新工作技能
const updateWorkerSkills = (worker) => {
  const types = formatServiceTypes(worker.serviceType)
  const skills = []

  if (types.includes('清洁服务')) {
    skills.push(
        { name: '家居清洁', level: 85 + Math.floor(Math.random() * 15) },
        { name: '厨房清洁', level: 80 + Math.floor(Math.random() * 20) },
        { name: '卫浴清洁', level: 90 + Math.floor(Math.random() * 10) }
    )
  }

  if (types.includes('维修服务')) {
    skills.push(
        { name: '家电维修', level: 75 + Math.floor(Math.random() * 25) },
        { name: '水电维修', level: 70 + Math.floor(Math.random() * 30) }
    )
  }

  if (types.includes('烹饪服务')) {
    skills.push(
        { name: '家常菜制作', level: 80 + Math.floor(Math.random() * 20) },
        { name: '营养搭配', level: 75 + Math.floor(Math.random() * 20) }
    )
  }

  if (types.includes('照护服务')) {
    skills.push(
        { name: '老人照护', level: 85 + Math.floor(Math.random() * 15) },
        { name: '儿童看护', level: 80 + Math.floor(Math.random() * 20) }
    )
  }

  if (types.includes('其他服务')) {
    skills.push(
        { name: '家居整理', level: 75 + Math.floor(Math.random() * 25) },
        { name: '园艺护理', level: 70 + Math.floor(Math.random() * 30) }
    )
  }

  // 如果没有匹配的技能，添加一些通用技能
  if (skills.length === 0) {
    skills.push(
        { name: '沟通能力', level: 80 + Math.floor(Math.random() * 20) },
        { name: '服务态度', level: 85 + Math.floor(Math.random() * 15) }
    )
  }

  workerSkills.value = skills
}

// 更新近期服务
const updateRecentServices = (worker) => {
  const types = formatServiceTypes(worker.serviceType)
  const services = []
  const customers = ['张先生', '李女士', '王先生', '赵女士', '陈女士', '刘先生']
  const today = new Date()

  // 只有在职人员有近期服务
  if (worker.status === '不在职') {
    recentServices.value = []
    return
  }

  for (let i = 0; i < 4; i++) {
    const serviceDate = new Date(today)
    serviceDate.setDate(today.getDate() - i * 7 - Math.floor(Math.random() * 5))

    const dateStr = serviceDate.toISOString().split('T')[0]
    const typeIndex = Math.floor(Math.random() * types.length)
    const customerIndex = Math.floor(Math.random() * customers.length)

    services.push({
      date: dateStr,
      serviceType: getSpecificService(types[typeIndex] || '基础服务'),
      customer: customers[customerIndex],
      duration: 2 + Math.floor(Math.random() * 4),
      status: i === 0 ? '进行中' : '已完成',
      rating: i === 0 ? 0 : (4 + Math.random())
    })
  }

  recentServices.value = services
}

// 根据服务类型获取具体服务
const getSpecificService = (type) => {
  const services = {
    '清洁服务': ['日常保洁', '深度清洁', '厨房清洁', '卫浴清洁', '家电清洗'],
    '维修服务': ['水管维修', '电器维修', '家具维修', '门窗维修'],
    '烹饪服务': ['日常烹饪', '宴会准备', '营养餐制作'],
    '照护服务': ['老人照护', '儿童看护', '婴儿护理'],
    '其他服务': ['家居整理', '园艺护理', '宠物照料']
  }

  const options = services[type] || ['基础服务']
  return options[Math.floor(Math.random() * options.length)]
}

// 更新客户评价
const updateCustomerReviews = (worker) => {
  // 如果不在职，则没有评价
  if (worker.status === '不在职') {
    customerReviews.value = []
    return
  }

  const expYears = getExperienceYears(worker.workExperience)
  const reviewCount = Math.min(expYears, 5)
  const reviews = []

  const customers = ['张先生', '李女士', '王先生', '赵女士', '陈女士', '刘先生']
  const positiveComments = [
    '服务态度非常好，工作认真负责，非常满意！',
    '非常专业，做事细致，会经常预约！',
    '工作速度快，质量高，很满意这次服务！',
    '态度好，认真负责，技术也很好，值得推荐！',
    '非常满意，服务超出预期，非常感谢！'
  ]

  const normalComments = [
    '整体服务不错，有些小细节可以再完善。',
    '服务质量挺好的，就是时间掌握还可以优化。',
    '服务态度很好，技术也不错，价格稍高。',
    '挺专业的，但沟通上有些小问题。'
  ]

  const today = new Date()

  for (let i = 0; i < reviewCount; i++) {
    const reviewDate = new Date(today)
    reviewDate.setDate(today.getDate() - i * 30 - Math.floor(Math.random() * 15))

    const dateStr = reviewDate.toISOString().split('T')[0]
    const customerIndex = Math.floor(Math.random() * customers.length)
    const rating = 3.5 + Math.random() * 1.5
    const isPositive = rating >= 4.5

    const commentList = isPositive ? positiveComments : normalComments
    const commentIndex = Math.floor(Math.random() * commentList.length)

    reviews.push({
      customer: customers[customerIndex],
      date: dateStr,
      rating: rating,
      content: commentList[commentIndex]
    })
  }

  customerReviews.value = reviews
}

// 加载更多评价
const loadMoreReviews = () => {
  ElMessage.info('更多评价加载中...')
}

// 编辑/添加对话框
const editDialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const workerFormRef = ref(null)
const workerForm = reactive({
  id: null,
  name: '',
  gender: '女',
  age: 30,
  serviceTypeArray: [],
  workExperience: '',
  joinDate: '',
  status: '在职'
})
const workerRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 18, max: 65, message: '年龄必须在18到65之间', trigger: 'blur' }
  ],
  serviceTypeArray: [
    { required: true, message: '请选择至少一种服务类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择工作状态', trigger: 'change' }
  ],
  joinDate: [
    { required: true, message: '请选择加入日期', trigger: 'change' }
  ]
}

// 添加家政人员
const handleAddWorker = () => {
  isEdit.value = false
  workerForm.id = null
  workerForm.name = ''
  workerForm.gender = '女'
  workerForm.age = 30
  workerForm.serviceTypeArray = []
  workerForm.workExperience = ''
  workerForm.joinDate = new Date().toISOString().split('T')[0]
  workerForm.status = '在职'

  editDialogVisible.value = true
}

// 编辑家政人员
// const handleEditWorker = (worker) => {
//   isEdit.value = true
//   workerForm.id = worker.id
//   workerForm.name = worker.name
//   workerForm.gender = worker.gender
//   workerForm.age = worker.age
//   workerForm.serviceTypeArray = formatServiceTypes(worker.serviceType)
//   workerForm.workExperience = worker.workExperience || ''
//   workerForm.joinDate = worker.joinDate
//   workerForm.status = worker.status
//
//   editDialogVisible.value = true
// }

// 删除家政人员 - 连接到真实后端接口
const handleDeleteWorker = (worker) => {
  ElMessageBox.confirm(`确认删除家政人员 ${worker.name} 吗？`, '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用真实的删除接口
      await deleteWorkerById(worker.id);

      // 成功删除后，更新本地数据
      allWorkers.value = allWorkers.value.filter(item => item.id !== worker.id);
      ElMessage.success('删除成功');

      // 更新筛选和分页
      applyLocalFilters();
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }).catch(() => {});
}

// 提交家政人员表单 - 连接到真实后端接口
const submitWorkerForm = () => {
  workerFormRef.value.validate(async valid => {
    if (!valid) return

    submitting.value = true

    // 处理serviceType数组转字符串
    const serviceType = workerForm.serviceTypeArray.join(',')

    // 构建提交的数据对象
    const submitData = {
      id: workerForm.id,
      name: workerForm.name,
      gender: workerForm.gender,
      age: workerForm.age,
      serviceType: serviceType,
      workExperience: workerForm.workExperience,
      joinDate: workerForm.joinDate,
      status: workerForm.status
    }

    try {
      if (isEdit.value) {
        // 编辑现有数据 - 使用真实的update接口
        await updateWorker(submitData);


        // 更新本地数据
        const index = allWorkers.value.findIndex(item => item.id === submitData.id);
        if (index !== -1) {
          // 保留不可见字段
          const original = allWorkers.value[index];
          allWorkers.value[index] = {
            ...original,
            ...submitData
          };
        }
        ElMessage.success('编辑成功');
      } else {
        // 添加新数据 - 假设有一个添加接口
        const response = await addWorker(submitData);

        // 添加成功后刷新数据
        await fetchWorkerData();
        ElMessage.success('添加成功');
      }

      editDialogVisible.value = false;
      // 更新筛选和分页
      applyLocalFilters();
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    } finally {
      submitting.value = false;
    }
  })
}

// 页面初始化时加载数据
onMounted(() => {
  fetchWorkerData();
});
</script>

<style scoped>
/* 原有样式保持不变... */

/* 添加下拉框自定义样式 */
:deep(.el-select .el-input__wrapper) {
  padding-left: 8px;
}

:deep(.select-tag) {
  margin-right: 5px;
}

:deep(.custom-select-dropdown .el-select-dropdown__item) {
  padding: 0 10px !important;
}

:deep(.select-option-content) {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

/* 覆盖Element Plus的默认内边距 */
:deep(.el-header), :deep(.el-aside), :deep(.el-main) {
  padding: 0;
  margin: 0;
}

:deep(.el-main) {
  --el-main-padding: 20px;
  padding: var(--el-main-padding);
}

.home-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
  position: absolute;
  left: 0;
  top: 0;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  z-index: 1000;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 20px;
  font-weight: bold;
  font-size: 18px;
}

.logo img {
  height: 32px;
  margin-right: 8px;
}

.nav-text {
  margin-left: 15px;
}

.header-left .el-icon {
  margin-right: 15px;
  font-size: 18px;
  cursor: pointer;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .el-icon {
  font-size: 20px;
  margin: 0 15px;
  cursor: pointer;
}

.client-btn {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
}

.user-info span {
  margin: 0 8px;
}

/* 主容器样式 */
.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  width: 100%;
  margin: 0;
  padding: 0;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #fff;
  height: 100%;
  box-shadow: 1px 0 4px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  z-index: 900;
  width: 64px !important;
  min-width: 64px;
  flex-shrink: 0;
  margin: 0;
  padding-left: 0;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 64px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
}

.menu-item span {
  font-size: 12px;
  margin-top: 5px;
}

.menu-item .el-icon {
  font-size: 20px;
}

.menu-item.active {
  color: #1989fa;
  background-color: #f0f7ff;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  overflow-y: auto;
  width: calc(100% - 64px);
  box-sizing: border-box;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 筛选区域样式 */
.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  padding: 10px;
}

/* 表格区域样式 */
.table-container {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.statistics {
  display: flex;
  gap: 10px;
}

.table-actions {
  display: flex;
  gap: 10px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 详情样式 */
.detail-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  font-size: 18px;
  margin: 0;
  font-weight: 600;
}

.detail-item {
  margin-bottom: 10px;
}

.detail-item .label {
  font-weight: 600;
  color: #606266;
  margin-right: 5px;
}

.service-types {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 10px 0;
}

.service-tag {
  margin-right: 5px;
}

.work-experience {
  margin: 15px 0;
  color: #606266;
  line-height: 1.6;
}

.stat-card {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  text-align: center;
  margin-bottom: 15px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  margin-top: 5px;
  font-size: 14px;
  color: #606266;
}

.skill-item {
  margin-bottom: 15px;
}

.skill-name {
  display: inline-block;
  width: 100px;
  font-weight: 500;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.review-item {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.reviewer-info {
  display: flex;
  align-items: center;
}

.reviewer-detail {
  margin-left: 10px;
}

.reviewer-name {
  font-weight: 600;
}

.review-date {
  font-size: 12px;
  color: #909399;
}

.review-content {
  color: #303133;
  line-height: 1.6;
}

.no-reviews {
  text-align: center;
  padding: 20px;
  color: #909399;
}
</style>
